home *** CD-ROM | disk | FTP | other *** search
- Path: oxy.rust.net!usenet
- From: ebennett@rust.net
- Newsgroups: comp.lang.c
- Subject: Re: quick decision: is n a power of 2?
- Date: Sun, 21 Jan 1996 19:49:30 GMT
- Organization: Rust Net - High Speed Internet in Detroit 810-642-2276
- Message-ID: <4dtqpq$sl2@oxy.rust.net>
- References: <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca> <4dpian$gij@oxy.rust.net> <9601201820.AA01752@dxmint.cern.ch>
- NNTP-Posting-Host: liv-11.rust.net
- X-Newsreader: Forte Free Agent 1.0.82
-
- Dan Pop <danpop@mail.cern.ch> wrote:
-
- >ebennett@rust.net writes:
-
- >>Given some number, there is a neat trick to generate a mask which will
- >>have exactly one bit set in it. The bit set will be the least
- >>significant non-zero bit in the original number:
- >>
- >> mask = ~number & number;
- >>
- >>Now, if number contained a single non-zero bit (and is therefore a
- >>power of 2), mask will be equal to number. Therefore:
- >>
- >> if (number == (~number & number))
- >> {
- >> /* number is a power of 2 */
- >> }
- >>
- >>Try it, you'll like it!
-
- >I don't think so. ~number & number will _always_ give 0. -number & number
- >will actually work, except for the case when number == 0. That is,
- >assuming a two's complement implementation. On a one's complement or
- >sign-magnitude implementation it won't work at all.
-
- >Yet another guy who makes a fool of himself because he's too lazy to
- >test his solution before posting.
-
- >Dan
-
- You are correct in that I made a typo in my message. ~ should have
- been -. There are also some limitations which did not occur to me,
- which you have rightly pointed out.
-
- I agree with the problem with 0, and that is easily checked for.
- Where would you run into a one's complement or sign-magnitude
- implementation?
-
- However, I do not feel that I made a fool of myself. Most of us are
- not perfect as you apparently are. The rest of us make mistakes, and
- learn from them. That does not make us fools.
-
- Earl
-
-
-